package main

import (
	"context"
	"ginfast/api/middleware"
	_ "ginfast/api/system"
	"ginfast/configs"
	"ginfast/initialize"
	"ginfast/pkg/ginx"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	if err := configs.Load("../../config.yaml"); err != nil {
		log.Fatalln(err)
	}
	log.Println("connect database.", initialize.Database())
	// gin.SetMode(gin.ReleaseMode)
	engine := gin.Default()
	// engine.Use(middleware.LoadTLS()) // https
	engine.Use(middleware.Cors()) // 跨域
	r := engine.Group("/api")
	r.StaticFS("/public", gin.Dir(configs.Public.String(), true))
	ginx.Use(r,
		middleware.UseJWTAuth(r.Group("")),
		// middleware.UseTokenAuth(r.Group("/api")),
	)
	s := ginx.ListenAndServe(engine, 8080, 60)
	// Wait for interrupt signal to gracefully shutdown the server with
	// a timeout of 5 seconds.
	quit := make(chan os.Signal)
	// kill (no param) default send syscanll.SIGTERM
	// kill -2 is syscall.SIGINT
	// kill -9 is syscall. SIGKILL but can"t be catch, so don't need add it
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shutdown Server ...")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	s.Shutdown(ctx)
	// catching gginx.Done(). timeout of 5 seconds.
	<-ctx.Done()
}
